<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="清算日期">
        <el-date-picker
          v-model="daterangeSettlementDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="合约编码" prop="contractCode">
        <el-input
          v-model="queryParams.contractCode"
          placeholder="请输入合约编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="成交价格" prop="executionPrice">
        <el-input
          v-model="queryParams.executionPrice"
          placeholder="请输入成交价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="成交数量" prop="executedQuantity">
        <el-input
          v-model="queryParams.executedQuantity"
          placeholder="请输入成交数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['trade:tradeRecord:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['trade:tradeRecord:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['trade:tradeRecord:remove']"
        >删除</el-button>
      </el-col>
      <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['trade:tradeRecord:import']">导入</el-button>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-share"
          size="mini"
          :disabled="multiple"
          @click="handleAssignClearGroup"
          v-hasPermi="['trade:tradeRecord:assign']"
        >分配清算组编号</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-close"
          size="mini"
          :disabled="multiple"
          @click="handleClearGroupNumber"
          v-hasPermi="['trade:tradeRecord:clear']"
        >清除清算组编号</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tradeRecordList">
      <el-table-column type="selection" width="25" align="center" />
<!--      <el-table-column label="主键id" align="center" prop="id"/>-->
      <el-table-column label="清算日期" align="center" prop="settlementDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.settlementDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="清算组编号" align="center" prop="clearGroupNumber" />
      <el-table-column label="合约编码" align="center" prop="contractCode" width="120"/>
      <el-table-column label="合约简称" align="center" prop="contractAbbreviation" width="140"/>
      <el-table-column label="买卖方向" align="center" prop="tradeDirection" width="80">
        <template slot-scope="scope">
          {{ scope.row.tradeDirection === 0 ? '买入' : '卖出' }}
        </template>
      </el-table-column>
      <el-table-column label="开平" align="center" prop="positionAction" >
        <template slot-scope="scope">
          {{ scope.row.positionAction === 0 ? '开仓' : '平仓' }}
        </template>
      </el-table-column>
      <el-table-column label="成交价格" align="center" prop="executionPrice" />
      <el-table-column label="成交数量" align="center" prop="executedQuantity" />
      <el-table-column label="成交金额" align="center" prop="executedAmount" />
      <el-table-column label="委托价格" align="center" prop="orderPrice" />
      <el-table-column label="委托数量" align="center" prop="orderQuantity" />
      <el-table-column label="类别" align="center" prop="optionType" >
        <template slot-scope="scope">
          {{ scope.row.optionType === 0 ? '认购' : '认沽' }}
        </template>
      </el-table-column>
      <el-table-column label="备兑" align="center" prop="covered">
        <template slot-scope="scope">
          {{ scope.row.covered === 0 ? '非备兑' : '备兑' }}
        </template>
      </el-table-column>
      <el-table-column label="委托号" align="center" prop="orderId" />
      <el-table-column label="委托时间" align="center" prop="orderTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="交易市场" align="center" prop="tradingMarket" width="120"/>
      <el-table-column label="合同编号" align="center" prop="contractNumber" width="120"/>
      <el-table-column label="印花税率" align="center" prop="stampDutyRate" />
      <el-table-column label="经手费" align="center" prop="brokerageFee" />
      <el-table-column label="证管费" align="center" prop="regulatoryFee" />
      <el-table-column label="清算费" align="center" prop="settlementFee" />
      <el-table-column label="过户费" align="center" prop="transferFee" />
      <el-table-column label="交易过户费" align="center" prop="transactionTransferFee" width="100"/>
      <el-table-column label="行权过户费" align="center" prop="exerciseTransferFee" width="100"/>
      <el-table-column label="交易规费" align="center" prop="transactionLevy" />
      <el-table-column label="佣金" align="center" prop="commission" />
      <el-table-column label="清算金额" align="center" prop="settlementAmount" />
      <el-table-column label="利润分组" align="center" prop="profitGroup" />
      <el-table-column label="交割月" align="center" prop="deliveryMonth" />
      <el-table-column label="清算标识" align="center" prop="clearFlag">
        <template slot-scope="scope">
          {{ scope.row.clearFlag === 0 ? '未清算' :
          scope.row.clearFlag === 1 ? '已清算' : '' }}
        </template>
      </el-table-column>
      <el-table-column label="杠杆数量" align="center" prop="leverageQuantity" />
      <el-table-column label="其他损益费" align="center" prop="otherPlFee" />
      <el-table-column label="其他损益描述" align="center" prop="otherPlDescription" />
      <el-table-column label="备用金" align="center" prop="reserveFund" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['trade:tradeRecord:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['trade:tradeRecord:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改成交记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="清算日期" prop="settlementDate">
          <el-date-picker clearable
            v-model="form.settlementDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择清算日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合约编码" prop="contractCode">
          <el-input v-model="form.contractCode" placeholder="请输入合约编码" />
        </el-form-item>
        <el-form-item label="合约简称" prop="contractAbbreviation">
          <el-input v-model="form.contractAbbreviation" placeholder="请输入合约简称" />
        </el-form-item>
        <el-form-item label="买卖方向" prop="tradeDirection">
          <el-input v-model="form.tradeDirection" placeholder="请输入买卖方向：0-买入，1-卖出" />
        </el-form-item>
        <el-form-item label="开平" prop="positionAction">
          <el-input v-model="form.positionAction" placeholder="请输入开平：0-开仓，1-平仓" />
        </el-form-item>
        <el-form-item label="成交价格" prop="executionPrice">
          <el-input v-model="form.executionPrice" placeholder="请输入成交价格" />
        </el-form-item>
        <el-form-item label="成交数量" prop="executedQuantity">
          <el-input v-model="form.executedQuantity" placeholder="请输入成交数量" />
        </el-form-item>
        <el-form-item label="成交金额" prop="executedAmount">
          <el-input v-model="form.executedAmount" placeholder="请输入成交金额" />
        </el-form-item>
        <el-form-item label="委托价格" prop="orderPrice">
          <el-input v-model="form.orderPrice" placeholder="请输入委托价格" />
        </el-form-item>
        <el-form-item label="委托数量" prop="orderQuantity">
          <el-input v-model="form.orderQuantity" placeholder="请输入委托数量" />
        </el-form-item>
        <el-form-item label="备兑" prop="covered">
          <el-input v-model="form.covered" placeholder="请输入备兑：0-非备兑，1-备兑" />
        </el-form-item>
        <el-form-item label="委托号" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入委托号" />
        </el-form-item>
        <el-form-item label="委托时间" prop="orderTime">
          <el-date-picker clearable
            v-model="form.orderTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择委托时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="交易市场" prop="tradingMarket">
          <el-input v-model="form.tradingMarket" placeholder="请输入交易市场" />
        </el-form-item>
        <el-form-item label="合同编号" prop="contractNumber">
          <el-input v-model="form.contractNumber" placeholder="请输入合同编号" />
        </el-form-item>
        <el-form-item label="印花税率" prop="stampDutyRate">
          <el-input v-model="form.stampDutyRate" placeholder="请输入印花税率" />
        </el-form-item>
        <el-form-item label="经手费" prop="brokerageFee">
          <el-input v-model="form.brokerageFee" placeholder="请输入经手费" />
        </el-form-item>
        <el-form-item label="证管费" prop="regulatoryFee">
          <el-input v-model="form.regulatoryFee" placeholder="请输入证管费" />
        </el-form-item>
        <el-form-item label="清算费" prop="settlementFee">
          <el-input v-model="form.settlementFee" placeholder="请输入清算费" />
        </el-form-item>
        <el-form-item label="过户费" prop="transferFee">
          <el-input v-model="form.transferFee" placeholder="请输入过户费" />
        </el-form-item>
        <el-form-item label="交易过户费" prop="transactionTransferFee">
          <el-input v-model="form.transactionTransferFee" placeholder="请输入交易过户费" />
        </el-form-item>
        <el-form-item label="行权过户费" prop="exerciseTransferFee">
          <el-input v-model="form.exerciseTransferFee" placeholder="请输入行权过户费" />
        </el-form-item>
        <el-form-item label="交易规费" prop="transactionLevy">
          <el-input v-model="form.transactionLevy" placeholder="请输入交易规费" />
        </el-form-item>
        <el-form-item label="佣金" prop="commission">
          <el-input v-model="form.commission" placeholder="请输入佣金" />
        </el-form-item>
        <el-form-item label="清算金额" prop="settlementAmount">
          <el-input v-model="form.settlementAmount" placeholder="请输入清算金额" />
        </el-form-item>
        <el-form-item label="利润分组" prop="profitGroup">
          <el-input v-model="form.profitGroup" placeholder="请输入利润分组" />
        </el-form-item>
        <el-form-item label="交割月" prop="deliveryMonth">
          <el-input v-model="form.deliveryMonth" placeholder="请输入交割月" />
        </el-form-item>
        <el-form-item label="清算标识" prop="clearFlag">
          <el-input v-model="form.clearFlag" placeholder="请输入清算标识：0-未清算，1-已清算" />
        </el-form-item>
        <el-form-item label="杠杆数量" prop="leverageQuantity">
          <el-input v-model="form.leverageQuantity" placeholder="请输入杠杆数量" />
        </el-form-item>
        <el-form-item label="其他损益费" prop="otherPlFee">
          <el-input v-model="form.otherPlFee" placeholder="请输入其他损益费" />
        </el-form-item>
        <el-form-item label="其他损益描述" prop="otherPlDescription">
          <el-input v-model="form.otherPlDescription" placeholder="请输入其他损益描述" />
        </el-form-item>
        <el-form-item label="备用金" prop="reserveFund">
          <el-input v-model="form.reserveFund" placeholder="请输入备用金" />
        </el-form-item>
        <el-form-item label="清算组编号" prop="clearGroupNumber">
          <el-input v-model="form.clearGroupNumber" placeholder="请输入清算组编号" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker clearable
            v-model="form.createdAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedAt">
          <el-date-picker clearable
            v-model="form.updatedAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
<!--          <div class="el-upload__tip" slot="tip">-->
<!--            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的交易数据-->
<!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTradeRecord, getTradeRecord, delTradeRecord, addTradeRecord, updateTradeRecord, assignClearGroup, clearGroupNumber} from "@/api/trade/tradeRecord"
import { getToken } from "@/utils/auth"
export default {
  name: "TradeRecord",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 成交记录表格数据
      tradeRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 更新时间时间范围
      daterangeSettlementDate: [],
      // 交易记录导入参数
      upload: {
        // 是否显示弹出层（交易记录导入）
        open: false,
        // 弹出层标题（交易记录导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的交易记录数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/trade/tradeRecord/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        settlementDate: null,
        contractCode: null,
        executionPrice: null,
        executedQuantity: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        contractNumber: [
          { required: true, message: "合同编号不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询成交记录列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeSettlementDate && '' != this.daterangeSettlementDate) {
        this.queryParams.params["beginSettlementDate"] = this.daterangeSettlementDate[0]
        this.queryParams.params["endSettlementDate"] = this.daterangeSettlementDate[1]
      }
      listTradeRecord(this.queryParams).then(response => {
        this.tradeRecordList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        settlementDate: null,
        contractCode: null,
        contractAbbreviation: null,
        tradeDirection: null,
        positionAction: null,
        executionPrice: null,
        executedQuantity: null,
        executedAmount: null,
        orderPrice: null,
        orderQuantity: null,
        optionType: null,
        covered: null,
        orderId: null,
        orderTime: null,
        tradingMarket: null,
        contractNumber: null,
        stampDutyRate: null,
        brokerageFee: null,
        regulatoryFee: null,
        settlementFee: null,
        transferFee: null,
        transactionTransferFee: null,
        exerciseTransferFee: null,
        transactionLevy: null,
        commission: null,
        settlementAmount: null,
        profitGroup: null,
        deliveryMonth: null,
        clearFlag: null,
        leverageQuantity: null,
        otherPlFee: null,
        otherPlDescription: null,
        reserveFund: null,
        clearGroupNumber: null,
        createdAt: null,
        updatedAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeSettlementDate = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加成交记录"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getTradeRecord(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改成交记录"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTradeRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addTradeRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除成交记录编号为"' + ids + '"的数据项？').then(function() {
        return delTradeRecord(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('trade/tradeRecord/export', {
        ...this.queryParams
      }, `tradeRecord_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "成交记录导入"
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('trade/tradeRecord/importTemplate', {
      }, `trade_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    /** 分配清算组编号按钮操作 */
    handleAssignClearGroup() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请至少选择一条记录");
        return;
      }

      this.$modal.confirm('确定要为选中的 ' + this.ids.length + ' 条记录分配清算组编号吗？')
        .then(() => {
          assignClearGroup(this.ids).then(response => {
            this.$modal.msgSuccess("分配成功");
            this.getList();
          }).catch(error => {
            this.$modal.msgError(error.msg || "分配失败");
          });
        })
        .catch(() => {});
    },
    /** 清除清算组编号按钮操作 */
    handleClearGroupNumber() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请至少选择一条记录");
        return;
      }

      this.$modal.confirm('确定要清除选中的 ' + this.ids.length + ' 条记录的清算组编号吗？')
        .then(() => {
          clearGroupNumber(this.ids).then(response => {
            this.$modal.msgSuccess("清除成功");
            this.getList();
          }).catch(error => {
            this.$modal.msgError(error.msg || "清除失败");
          });
        })
        .catch(() => {});
    }
  }
}
</script>
